﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using IView.DiaryAndTracking;
using Presenter.DiaryAndTracking;
using DataTransferObject.DiaryAndTrackingTask.SupportClassForUpdateTask;

namespace JSKE.DiaryAndTracking
{
    public partial class TrackingTask : FormLang, ITrackingTaskForm
    {
        private PresenterTrackingTaskForm _presenter;
        private Double[] timeDiv = new Double[] { 0, -1, -7, -30 };
        private DateTime _viewFrom = DateTime.Now.Date;
        private DateTime _viewTo = DateTime.Now.Date.AddDays(1.0);
        private List<TaskWorked> listTaskWorked = new List<TaskWorked>();

        private BindingSource _bindingSource = new BindingSource();

        private Boolean isDataChanged = false;
        private TaskWorked currentSelectedTW = new TaskWorked();
        public TrackingTask()
        {
            //InitializeComponent();
            dtpkFrom.Enabled = false;
            dtpkTo.Enabled = false;
            cbbTime.SelectedIndex = 0;
            _presenter = new PresenterTrackingTaskForm(this, DATA_MODE);
            listTaskWorked = _presenter.loadTaskWorked(_viewFrom, _viewTo);
            BindListView(listTaskWorked);
            btnUpdate.Enabled = false;

        }
        public TrackingTask(string message)
        {
            //InitializeComponent();
        }
        private void btnTaskReport_Click(object sender, EventArgs e)
        {
            if (isDataChanged)
            {
                DialogResult res = MessageBox.Show("Do you want to save changes data?", "Notice",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (res == System.Windows.Forms.DialogResult.Yes)
                {
                    doSave();
                }
            }
            TaskReport taskReportForm = new TaskReport();
            taskReportForm.ShowDialog(this);
        }

        private void btnAddTask_Click(object sender, EventArgs e)
        {
            TaskForm taskForm = new TaskForm();
            taskForm.ShowDialog(this);
        }

        private void cbbTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            dtpkFrom.Enabled = false;
            dtpkTo.Enabled = false;
            if(cbbTime.SelectedIndex == 4)
            {
                _viewFrom = DateTime.Now.Date.AddYears(-100);
                _viewTo = DateTime.Now.Date.AddYears(100);
            }
            else if (cbbTime.SelectedIndex == 5)
            {
                dtpkFrom.Value = DateTime.Now.Date;
                dtpkTo.Value = DateTime.Now.Date;
                dtpkFrom.Enabled = true;
                dtpkTo.Enabled = true;
            }
            else
            {
                _viewFrom = DateTime.Now.Date.AddDays(timeDiv[cbbTime.SelectedIndex]);
            }
            dtpkFrom.Value = _viewFrom;
            dtpkTo.Value = _viewTo;
        }

        private void dtpkFrom_ValueChanged(object sender, EventArgs e)
        {
            _viewFrom = dtpkFrom.Value.Date;
        }

        private void dtpkTo_ValueChanged(object sender, EventArgs e)
        {
            _viewTo = dtpkTo.Value.Date;
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            if (_viewFrom > _viewTo)
            {
                MessageBox.Show("You Must choose a valid Timespan. From <= To", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                this.listTaskWorked = _presenter.loadTaskWorked(_viewFrom, _viewTo);
                BindListView(listTaskWorked);
            }
        }

        private void BindListView(List<TaskWorked> list)
        {

            listViewTaskWorked.SuspendLayout();

            listViewTaskWorked.Items.Clear();

            foreach (TaskWorked tw in list)
            {
                ListViewItem item = new ListViewItem(new string[]{
                                    tw.TaskName,
                                    Convert.ToString(tw.AdditionalWork),
                                    Convert.ToString(tw.RemainingTime),
                                    Convert.ToString(tw.TaskCode),
                                    tw.TimeStamp.ToString()});
                listViewTaskWorked.Items.Add(item);
            }
            listViewTaskWorked.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            listViewTaskWorked.ResumeLayout();
        }

        private void listViewTaskWorked_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewTaskWorked.SelectedItems.Count > 0)
            {
                TaskWorked tskW = listTaskWorked[listViewTaskWorked.SelectedIndices[0]];
                txtTaskName.Text = tskW.TaskName;
                txtNotes.Text = tskW.Notes;
                txtAddWork.Text = Convert.ToString(tskW.AdditionalWork);
                txtRemain.Text = Convert.ToString(tskW.RemainingTime);
                dtpkTimeStamp.Value = tskW.TimeStamp;
                currentSelectedTW = tskW;
                lblSaveResult.Text = "";

                btnUpdate.Enabled = true;
            }
            else
            {
                btnUpdate.Enabled = false;
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (isInputTxtInvalid())
            {
                MessageBox.Show("Datum in Textbox are invalid", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                currentSelectedTW.AdditionalWork = int.Parse(txtAddWork.Text);
                currentSelectedTW.Notes = txtNotes.Text;
                currentSelectedTW.RemainingTime = int.Parse(txtRemain.Text);
                currentSelectedTW.TaskName = txtTaskName.Text;
                lblSaveResult.Text = "";
                BindListView(listTaskWorked);

                isDataChanged = true;
                btnUpdate.Enabled = false;
            }
        }

        private Boolean isInputTxtInvalid()
        {
            Boolean result = txtTaskName.Text.Trim().Equals("") ||
                txtRemain.Text.Trim().Equals("") || txtAddWork.Text.Trim().Equals("");
            
            try
            {
                int.Parse(txtAddWork.Text.ToString());
                int.Parse(txtRemain.Text.ToString());
                result = result || false;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = true;
            }
            return result;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            doSave();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }

        private void doSave()
        {
            try
            {
                List<TaskWorked> listTW = new List<TaskWorked>();
                for (int i = 0; i < listTaskWorked.Count; i++)
                {
                    listTW.Add(listTaskWorked[i]);
                }
                _presenter.saveTaskWorked(listTW);
                isDataChanged = false;
                lblSaveResult.Text = "Save completed.";
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error while trying to save the Tracking Task Data because: " + ex.Message,
                    "Notice", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void TrackingTask_Closing(object sender, FormClosingEventArgs e)
        {
            if (isDataChanged)
            {
                DialogResult res = MessageBox.Show("Do you want to save changes data?", "Notice",
                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (res == System.Windows.Forms.DialogResult.Yes)
                {
                    doSave();
                    this.Close();
                }
                else if (res == System.Windows.Forms.DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }

        private void loadTaskReport()
        {
            _bindingSource.DataSource = _presenter.loadTaskReport();
            dtgrvReport.DataSource = _bindingSource.DataSource;
            foreach (DataGridViewRow drw in dtgrvReport.Rows)
            {
                String checkStr = drw.Cells[7].Value.ToString();
                if (checkStr != "")
                {
                    drw.DefaultCellStyle.BackColor = Color.Yellow;
                }
            }
        }
        private void loadSummaryReport()
        {
            _bindingSource.DataSource = _presenter.loadSummaryReport();
            dtgrvReport.DataSource = _bindingSource.DataSource;
            foreach (DataGridViewRow drw in dtgrvReport.Rows)
            {
                String checkStr = drw.Cells[3].Value.ToString();
                if (checkStr != "")
                {
                    drw.DefaultCellStyle.BackColor = Color.Yellow;
                }
            }
        }

        private void rdbProject_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbProject.Checked)
            {
                loadSummaryReport();
            }
        }

        private void rdbTask_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbTask.Checked)
            {
                loadTaskReport();
            }
        }

        private void OpenTaskItem(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (rdbTask.Checked)
                {
                    int taskID = int.Parse(dtgrvReport.Rows[e.RowIndex].Cells[0].Value.ToString());
                    TaskForm taskForm = new TaskForm(_presenter.getTaskByID(taskID));
                    taskForm.ShowDialog(this);
                }

            }
            catch
            {
                MessageBox.Show("You clicked on the wrong place",
                    "Important Note", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }

    
}
